#!/usr/bin/env python3

# Copyright (c) 2005-2014 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


import os
import json
import mrget
from datetime import datetime
from iptvwh import GameInfo, GameFileInfo
from iptvwh import EwProvider, ProviderNotSynchronized, BadProviderContent, SourceNotInProvider


class ProviderImpl(EwProvider):

    @property
    def name(self):
        return "Free-TV"

    @property
    def homepage(self):
        return "https://github.com/Free-TV/IPTV"

    @property
    def supported_element_types(self):
        return ["ipvt-live-source"]

    @property
    def last_sync_datetime(self):
        return datetime.min

    def sync(self, common):
        url = mrget.target_urls("mirror://github-usercontent/Free-TV/IPTV/master/playlist.m3u8")




        repoDir = os.path.join(common.cache_dir, "repo")
        os.makedirs(repoDir, exist_ok=True)
        robust_layer.simple_git.pull(repoDir, reclone_on_failure=True, url="https://github.com/rwv/chinese-dos-games")

    def has_game(self, common, platform_name, game_name):
        data = self._parseGamesJson(common.cache_dir)
        if data is None:
            raise ProviderNotSynchronized(self.name)

        if platform_name != 'MS-DOS':
            return False
        if game_name not in data:
            return False
        return True

    def list_games(self, common):
        data = self._parseGamesJson(common.cache_dir)
        if data is None:
            raise ProviderNotSynchronized(self.name)

        ret = []
        for k, v in data.items():
            if k != v["identifier"]:
                raise BadProviderContent(self.name, "Bad data for game \"%s\" in data source \"%s\"" % (k, self.name))
            ret.append(('MS-DOS', k))
        return ret

    def get_game_info(self, common, platform_name, game_name):
        data = self._parseGamesJson(common.cache_dir)
        if data is None:
            raise ProviderNotSynchronized(self.name)

        if platform_name == 'MS-DOS':
            raise SourceNotInProvider(self.name, platform_name, game_name)

        data = data.get(game_name)
        if data is None:
            raise SourceNotInProvider(self.name, platform_name, game_name)

        ret = GameInfo.from_parameters(
            default_language="zh_CN",
            names=self._toNames(data),
            release_year=ret.get("releaseYear"),
            files=self._toFiles(data, common.cache_dir)
        )
        return ret

    def _parseGamesJson(self, cacheDir):
        jsonData = None
        with open(os.path.join(cacheDir, "repo", "game.json"), "r") as f:
            jsonData = json.load(f)["games"]
        return jsonData

    def _toNames(self, oneGameData):
        ret = {}
        if "zh-Hans" in oneGameData["name"]:
            ret["zh_CN"] = oneGameData["name"]["zh-Hans"]
        if "zh-Hant" in oneGameData["name"]:
            ret["zh_TW"] = oneGameData["name"]["zh-Hant"]
        if "en" in oneGameData["name"]:
            ret["en_US"] = oneGameData["name"]["en"]
        return ret

    def _toFiles(self, oneGameData, cacheDir):
        ret = {}
        ret[GameFileInfo.StandardType.COVER] = {
            GameFileInfo.StandardProperty.NAME: oneGameData["coverFilename"],
            GameFileInfo.StandardProperty.URL: "file://%s/%s/%s" % (os.path.join(cacheDir, "repo", "img"), oneGameData["identifier"], oneGameData["coverFilename"]),
        }
        ret[GameFileInfo.StandardType.MAIN_GAME_DATA] = {
            GameFileInfo.StandardProperty.NAME: "%s.zip" % (oneGameData["identifier"]),
            GameFileInfo.StandardProperty.URL: "mirror://dos-bin/%s.zip" % (oneGameData["identifier"]),
            GameFileInfo.StandardProperty.SIZE: oneGameData["filesize"],
            GameFileInfo.StandardProperty.HASH_SHA256: oneGameData["sha256"],
        }
        return ret
